package com.atguigu.biz.service.impl;

import java.util.Arrays;
import java.util.List;
import com.atguigu.biz.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.biz.mapper.BizKnowledgeMapper;
import com.atguigu.biz.domain.BizKnowledge;
import com.atguigu.biz.service.IBizKnowledgeService;
import com.atguigu.biz.service.IEmbeddingStoreService;

/**
 * 知识库Service业务层处理
 * 
 * @author kkdulx
 * @date 2025-10-30
 */
@Service
public class BizKnowledgeServiceImpl implements IBizKnowledgeService 
{
    @Autowired
    private BizKnowledgeMapper bizKnowledgeMapper;

    @Autowired
    private IEmbeddingStoreService embeddingStoreService;

    /**
     * 查询知识库
     * 
     * @param id 知识库主键
     * @return 知识库
     */
    @Override
    public BizKnowledge selectBizKnowledgeById(Long id)
    {
        return bizKnowledgeMapper.selectBizKnowledgeById(id);
    }

    /**
     * 查询知识库列表
     * 
     * @param bizKnowledge 知识库
     * @return 知识库
     */
    @Override
    public List<BizKnowledge> selectBizKnowledgeList(BizKnowledge bizKnowledge)
    {
        return bizKnowledgeMapper.selectBizKnowledgeList(bizKnowledge);
    }

    /**
     * 新增知识库
     * 
     * @param bizKnowledge 知识库
     * @return 结果
     */
    @Override
    public int insertBizKnowledge(BizKnowledge bizKnowledge)
    {
        bizKnowledge.setCreateTime(DateUtils.getNowDate());
        int result = bizKnowledgeMapper.insertBizKnowledge(bizKnowledge);
        // 调用向量存储服务处理文件上传
        if (result > 0) {
            embeddingStoreService.upload(bizKnowledge);
            // 更新向量ID到数据库
            bizKnowledgeMapper.updateBizKnowledge(bizKnowledge);
        }
        return result;
    }

    /**
     * 修改知识库
     * 
     * @param bizKnowledge 知识库
     * @return 结果
     */
    @Override
    public int updateBizKnowledge(BizKnowledge bizKnowledge)
    {
        bizKnowledge.setUpdateTime(DateUtils.getNowDate());
        return bizKnowledgeMapper.updateBizKnowledge(bizKnowledge);
    }

    /**
     * 批量删除知识库
     * 
     * @param ids 需要删除的知识库主键
     * @return 结果
     */
    @Override
    public int deleteBizKnowledgeByIds(Long[] ids)
    {
        //根据ids查找vectorIds
        String vectorIdList = bizKnowledgeMapper.selectVectorIdListByIds(ids);
        //将文件从向量数据库删除
        embeddingStoreService.remove(Arrays.asList(vectorIdList.split(",")));
        return bizKnowledgeMapper.deleteBizKnowledgeByIds(ids);
    }

    /**
     * 删除知识库信息
     * 
     * @param id 知识库主键
     * @return 结果
     */
    @Override
    public int deleteBizKnowledgeById(Long id)
    {
        return bizKnowledgeMapper.deleteBizKnowledgeById(id);
    }
}